import { createRouter, createWebHistory } from "vue-router";
const CommonRoutes = () => import("@/router/commonRoutes.vue");

const SysIindex = () => import("@/views/sys/index.vue");
const SysPractice = () => import("@/views/sys/practice.vue");
const UserPractice = () => import("@/views/user/practice.vue");

const Login = () => import("@/views/login.vue");
const routes = [
  {
    path: "/login",
    name: "login",
    hidden: true,
    component: Login,
  },
  {
    path: "/sys",
    name: "sys",
    component: CommonRoutes,
    redirect: "/sysIndex",
    children: [
      {
        path: "/sysIndex",
        name: "sysIndex",
        component: SysIindex,
        meta: { title: "试卷管理" },
      },
      {
        path: "/sysPractice",
        name: "syspractice",
        component: SysPractice,
        meta: { title: "课题练习" },
      },
    ],
  },
  {
    path: "/user",
    name: "user",
    component: CommonRoutes,
    redirect: "/userPractice",
    children: [
      {
        path: "/userPractice",
        name: "userpractice",
        component: UserPractice,
        meta: { title: "课题练习" },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
});

const whiteList = ["login"];
router.beforeEach(async (to, from, next) => {
  const token = sessionStorage.getItem("token");
  const userInfo = sessionStorage.getItem("userInfo");
  if (token) {
    if (to.path === "/login") {
      if (userInfo.type == 1) next({ path: "/sys" });
      if (userInfo.type == 2) next({ path: "/user" });
    } else {
      next();
    }
  } else {
    if (whiteList.includes(to.name)) {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});

router.afterEach(() => {});

export default router;
